import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'bzFixed'
})
export class FixedPipe implements PipeTransform {

  transform(value: string | number, digits = 2): any {
    // 首先判断无法转换为数字的情况
    if (typeof value !== 'string' && typeof value !== 'number') {
      return '';
    }

    if (value !== value) {
      return '';
    }

    if (typeof value === 'string') {
      value = parseFloat(value);
      if (Number.isNaN(value)) {
        return '';
      }
    }

    if (value > -0.001 && value < 0.001) {
      return 0;
    }

    const num = this._transform(value, digits);

    if (value - +num + 0.000000000001 >= 0.01) {
      return this._calcFloat(num);
    }

    return num;
  }

  _transform(value: string | number, digits) {
    const [intNum, floatNum = ''] = value.toString().split('.');
    const _floatNum = floatNum.substr(0, digits).padEnd(digits, '0');
    return intNum + '.' + _floatNum;
  }

  _calcFloat(num) {
    const [intNum, [floatNum1, floatNum2]] = num.split('.');
    if (floatNum1 === '9' && floatNum2 === '9') {
      return `${+intNum + 1}.00`;
    } else if (floatNum2 === '9') {
      return `${intNum}.${+floatNum1 + 1}0`;
    } else {
      return `${intNum}.${floatNum1}${+floatNum2 + 1}`;
    }
  }
}
